package com.ly.mpayment.rest.up.longzhang;

import com.alibaba.fastjson.JSONObject;
import com.ly.mpayment.core.secuity.MD5;
import com.ly.mpayment.core.util.*;
import com.ly.mpayment.persist.entity.UpOrder;
import com.ly.mpayment.persist.entity.UpShopInfo;
import com.ly.mpayment.persist.service.downrechargeflow.IDownRechargeFlowService;
import com.ly.mpayment.persist.service.downshopinfo.IDownShopInfoService;
import com.ly.mpayment.persist.service.uporder.IUporderService;
import com.ly.mpayment.persist.service.upshopinfo.IUpShopInfoService;
import com.ly.mpayment.rest.recharge.RechargeRest;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import javax.ws.rs.POST;
import javax.ws.rs.Path;

@Component
@Path("longzhang")
public class LongZhangRest {

    Logger logger = Logger.getLogger(LongZhangRest.class);

    @Autowired
    IUporderService upOrderService;

    @Autowired
    private ThreadPoolTaskExecutor taskExecutor;

    @Autowired
    IDownRechargeFlowService flowService;

    @Autowired
    IDownShopInfoService shopService;

    @Autowired
    IUpShopInfoService upShopInfoService;

    @SuppressWarnings("static-access")
    @Path("callBack")
    @POST
    public String callBack(String data) {
        logger.info("longzhang_callback:" + data);
        if (!StringUtils.isBlank(data)) {
           try{
               JSONObject jsonD = JSONObject.parseObject(data);
               //支付结果 1 成功 2失败
               UpOrder order = upOrderService.findById(jsonD.getString("orderID"));
               if (order != null && jsonD.getString("status").equals("1") && order.getStatus() == Config.status[0]) {
                   order.setRemark(jsonD.containsKey("sn") ? jsonD.getString("sn") : jsonD.getString("status"));
                   RechargeRest.successUpOrder.add(order);
                   jsonD.clear();
                   jsonD.put("code",0);
                   return jsonD.toString();
               } else if (order != null && order.getStatus() == Config.status[0] && jsonD.getString("status").equals("2")) {
                   order.setRemark(jsonD.getString("status"));
                   RechargeRest.failtUpOrder.add(order);
                   jsonD.clear();
                   jsonD.put("code",0);
                   return jsonD.toString();
               } else {
                   logger.info("longzhang_not_found_order:" + jsonD.getString("orderId") + "," + order);
               }
           }catch (Exception e){
               e.printStackTrace();
           }
        }
        JSONObject jsonD = new JSONObject();
        jsonD.clear();
        jsonD.put("code",0);
        return jsonD.toJSONString();
    }


    /**
     * 订单提交
     *
     * @param order
     * @param shop
     */
    public void commitOrder(UpOrder order, UpShopInfo shop) {

        JSONObject data = new JSONObject();
        data.put("orderID",order.getUporderuuid());
        data.put("phone",order.getUpphonenum());
        data.put("userID",shop.getAppId());
        data.put("amount",order.getUpShopPro().getUpfacevalue());
        //md5(amount=xx&orderID=xxx&phone=xxx&userID=xxx&key=xxxx)
        data.put("sign",MD5.md5("amount="+order.getUpShopPro().getUpfacevalue()+"&orderID="+order.getUporderuuid()
                +"&phone="+order.getUpphonenum()+"&userID="+shop.getAppId()+"&key="+shop.getUpkey()));
        data.put("callbackUrl",shop.getOrderCallAddress());
        data.put("sp",order.getOperators().equals("2edb5b9c-9f99-11e7-9dc0-fcaa1456507e")
                ? "1" : order.getOperators().equals("2ee16927-9f99-11e7-9dc0-fcaa1456507e")
                ? "3" : order.getOperators().equals("2ee70961-9f99-11e7-9dc0-fcaa1456507e")
                ? "2" : "");
        data.put("province",order.getProvince());
        String result = HttpClient.post(shop.getOrderCommitAddress(),data.toString());
        logger.info("longzhang_result:"+result+","+order.getUpphonenum()+",:"+data.toString());
        try {
//            code	number	是	0成功 其它失败
//            msg	string	是	提示信息
//            data	json	否	额外信息 见下表
            JSONObject res = JSONObject.parseObject(result);
            //提交成功
            if( res.containsKey("code") && res.getString("code").equals("0")) {
                upOrderService.updateUpOrderMsg(order, res.getJSONObject("data").getString("platOrderID"), res.containsKey("msg") ? res.getString("msg") : res.getString("code"));
            }else if(res.containsKey("code") && !res.getString("code").equals("0")) {
                order.setRemark( res.getString("msg"));
                RechargeRest.failtUpOrder.add(order);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.info(e.getMessage());
            upOrderService.addOrderMsg(order,"提单异常需要人工");
        }
    }

    /**
     * 订单查询
     * @param upOrder
     * @param shopInfo
     */
    public void queryOrder(UpOrder upOrder, UpShopInfo shopInfo) {
        JSONObject data = new JSONObject();
        data.put("orderID", upOrder.getUporderuuid());
        data.put("userID", shopInfo.getAppId());
        data.put("stamp", System.currentTimeMillis());
        //签名 md5(orderID=xxx&stamp=xxx&userID=xxx&key=xxxx)
        data.put("sign", MD5.md5("orderID="+upOrder.getUporderuuid()+"&stamp="+data.getString("stamp")+"&userID="+shopInfo.getAppId()+"".concat("&key="+shopInfo.getUpkey())));
        String result =  HttpClient.httpGetUrl(shopInfo.getOrderStatusAddress().concat("?")+StringSort.jsonToString(data));
        logger.info("longzhangqueryOrder:"+upOrder.getUpphonenum()+":"+result+","+StringSort.jsonToString(data));
        if (!StringUtils.isBlank(result)) {
            JSONObject jsonD = JSONObject.parseObject(result);
            if(jsonD.containsKey("code") && jsonD.getString("code").equals("0")){
                UpOrder order = upOrderService.findById(jsonD.getJSONObject("data").getString("orderID"));
                // status number	支付结果 0无效(订单创建失败时) 1等待支付 2支付成功 3支付失败
                if (order != null && jsonD.getJSONObject("data").getString("status").equals("2") && order.getStatus() == Config.status[0]) {
                    order.setRemark(jsonD.containsKey("msg") ? jsonD.getString("msg") : jsonD.getJSONObject("data").getString("status"));
                    RechargeRest.successUpOrder.add(order);
                } else if (order != null && order.getStatus() == Config.status[0]
                        && (jsonD.getJSONObject("data").getString("status").equals("3") ||
                        jsonD.getJSONObject("data").getString("status").equals("2") ||
                        jsonD.getJSONObject("data").getString("status").equals("0"))) {
                    order.setRemark(jsonD.getString("msg"));
                    RechargeRest.failtUpOrder.add(order);
                } else {
                    logger.info("longzhang_not_found_order:" + jsonD.getJSONObject("data").getString("orderID") + "," + order.getUpphonenum());
                }
                //:{"code":2,"msg":"没有该订单"}
            }else if(jsonD.getString("code").equals("2")){
                upOrder.setRemark(jsonD.getString("msg"));
                RechargeRest.failtUpOrder.add(upOrder);
            } else{
                logger.info("longzhang_not_found_order:" + result+ "," + upOrder.getUpphonenum());
            }
        }
    }

}
